from rest_framework_mongoengine.viewsets import ModelViewSet
from .models import CiType, Ci
from .serializers import CiTypeSerializer, CiSerializer, CiTypeWithFieldsSerializer
from rest_framework.decorators import action
from rest_framework.response import Response
from utils.permissions import CRUDDocumentPermissions
from rest_framework.permissions import IsAuthenticated

class BaseCmdbModelViewSet(ModelViewSet):
    permission_classes = [IsAuthenticated, CRUDDocumentPermissions]

class CiTypeViewSet(BaseCmdbModelViewSet):  # /cmdb/citypes/
    queryset = CiType.objects.all()
    serializer_class = CiTypeSerializer
    mongo_search_fields = ['name', 'label']

    @action(methods=['GET'], detail=False)
    def all(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def get_serializer_class(self):
        print('+@#' * 30)
        print(self.kwargs)
        if 'id' in self.kwargs:# or ('name' in self.kwargs and 'version' in self.kwargs):
            return CiTypeWithFieldsSerializer
        return super().get_serializer_class()

    @action(detail=False, url_path="(?P<name>[^/.]+)/(?P<version>\d+)")  # detail URL带pk
    def get_by_name_and_version(self, request, name, version):
        print(name, version, "@@#$$$") # 做什么？ 类似于  retrieve get_object
        instance = self.get_queryset().get(name=name, version=version)
        # serializer = self.get_serializer(instance)
        serializer = CiTypeWithFieldsSerializer(instance)
        return Response(serializer.data)


class CiViewSet(BaseCmdbModelViewSet): # CRUD基本实现了
    queryset = Ci.objects.all()
    serializer_class = CiSerializer
    mongo_search_fields = ['fields__name', 'fields__value']

